//
//  GYXStatusPictureView.swift
//  GYXWeibo
//
//  Created by Twisal on 2017/3/10.
//  Copyright © 2017年 Twisal. All rights reserved.
//

import UIKit

class GYXStatusPictureView: UIView {
    /// 高度约束
    @IBOutlet private var heightCons: NSLayoutConstraint!
    
    /// 视图模型
    var viewModel: GYXStatusViewModel? {
        didSet {
            calViewSize()
            urls = viewModel?.picUrls
        }
    }
    
     /// 计算视图尺寸
     private func calViewSize() {
        
        // 1, 单图,设置第一张图片视图的原始尺寸
        if viewModel?.picUrls?.count == 1 {
            let iv = subviews[0]
            let size = viewModel?.pictureViewSize ?? CGSize()
            print("单图的尺寸为:\(size)")
            iv.frame = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: size.width, height: size.height - WBStatusPictureViewOutterMargin)
        // 2, 多图, 恢复九宫格的尺寸
        } else {
            let iv = subviews[0]
            iv.frame = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
        }
        heightCons.constant = viewModel?.pictureViewSize.height ?? 0
    }
    
    /// 图片模型数组
    private var urls: [GYXStatusPicture]? {
        didSet {
            // 1, 隐藏所有视图
            for iv in subviews {
                iv.isHidden = true
            }
            
            // 2, 为视图设置图片 
            var index = 0
            for url in urls ?? [] {
                
                if index == 2 && urls?.count == 4 {
                    index += 1
                }
                // 去除对应的图片视图
                let iv = subviews[index] as! UIImageView
                // 为视图设置图片
                iv.cz_setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                // 显示当前视图
                iv.isHidden = false
                index += 1
            }
            
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        setupUI()
    }
}

// MARK: - UI设置
extension GYXStatusPictureView {
    
    /// UI设置
    fileprivate func setupUI() {
        // 设置整个视图的背景颜色
        backgroundColor = superview?.backgroundColor
        // 设置整个配图视图超出部分裁剪
        clipsToBounds = true
        let count = 3
        let rect = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
        for i in 0 ..< count * count {
            let iv = UIImageView()
            // 设置 contentMode
            iv.contentMode = .scaleAspectFill
            iv.clipsToBounds = true
            // 行 -> Y
            let row = CGFloat(i / count)
            // 列 -> X
            let col = CGFloat(i % count)
            // x, y 偏移量
            let xyOffset = WBStatusPictureItemWidth + WBStatusPictureViewInnerMargin
        
            iv.frame = rect.offsetBy(dx: col * xyOffset, dy: row * xyOffset)
            addSubview(iv)
        }
    }
}
